package fr.uvsq.isty.bdh.hchess.gui.game;

import fr.uvsq.isty.bdh.hchess.engine.GameData;
import fr.uvsq.isty.bdh.hchess.gui.style.Style;
import ictk.boardgame.chess.ChessPiece;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JPanel;

/**
 * A Jpanel that displays the piece captured by one of the other player.
 * @author Rémi Dubois <RemiEric.Dubois@gmail.com>
 */
public class CapturedPieceDisplay extends JPanel implements Observer {
    private boolean isBlack;
    private ChessPiece[] capturedPieces;
    private Style style; /** Board style singleton */
    
    /**
     * @param isBlack true if it the piece captured by the black player we want to display
     */
    public CapturedPieceDisplay(boolean isBlack) {
        this.setPreferredSize(new Dimension(
                (BoardDisplay.DEFAULT_CASE_WIDTH/2),
                (BoardDisplay.DEFAULT_CASE_HEIGHT*8)));
        
        try {
            this.style = Style.getInstance();
        } catch (IOException ex) {
        }
        
        this.isBlack = isBlack;
        this.capturedPieces = null;
        
        this.repaint();
    }
    
    @Override
    public void paintComponent(Graphics g) {
        Image bg = style.getBGImage();
        g.setColor(Color.GRAY);
        
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        g.drawImage(bg, 0, 0, this.getWidth(), this.getHeight(), this);
        
        if(capturedPieces != null) {
            int i = 0;
            for (ChessPiece p : capturedPieces) {
                drawPiece(p, i, g);
                i++;
            }
        }
    }

    public void update(Observable o, Object arg) {
        if(o instanceof GameData) {
            GameData gameData = (GameData) o;
            
            capturedPieces = gameData.getCapturedPieces(!isBlack);
            
            this.repaint();
        }
    }
    
    /**
     * Draw a piece at the indicated position
     * @param piece the kind of piece
     * @param row the row in wich we display the piece
     * @param g
     */
    private void drawPiece(ChessPiece piece, int row, Graphics g) {
        if(row < (16)) {
            Image image = style.getPieceImage(piece.toString(), piece.isBlack());
            int x = 0;
            int y = ((row*this.getHeight())/16);
            g.drawImage(
                    image, 
                    x, 
                    y, 
                    (BoardDisplay.DEFAULT_CASE_WIDTH/2), 
                    (BoardDisplay.DEFAULT_CASE_HEIGHT/2), 
                    this);
        }
    }
    
}
